import { Card } from "antd";
import React, { useEffect } from "react";
import { Button, Form, Input,message } from "antd";
import style from "../index.module.css";
import {
  addHospitalSetListRequire,
  getHospitalByIdRequest,
  updateHospitalByIdRequire
} from "@/api/hospital/hospitalSet";
import { addHospitalSetListParams } from "@/api/hospital/model/hospitalSetType";
import { useNavigate, useParams } from "react-router-dom";

export default function HospitalAddOrUpdate() {
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const { id } = useParams();
  // console.log(id);

  useEffect(() => {
    if (id) {
      const setHospitalData = async () => {
        const result = await getHospitalByIdRequest(id);
        // console.log(result);
        form.setFieldsValue(result);
      };
      setHospitalData();
    }
  }, []);

  const getHospitalListHandle = async (data: addHospitalSetListParams) => {
    console.log(data);    
    if (id) {
      await updateHospitalByIdRequire({id,...data});
      message.success("修改成功!")
      navigate("/syt/hospital/hospitalset");
    } else {
      await addHospitalSetListRequire(data);
      message.success("添加成功!")
      navigate("/syt/hospital/hospitalset");
    }
  };
  const goBackToLastHandle = () => {
    navigate(-1);
  };

  return (
    <div>
      <Card>
        <Form
          form={form}
          name="basic"
          onFinish={getHospitalListHandle}
          labelCol={{ span: 2 }}
          wrapperCol={{ span: 22 }}
        >
          <Form.Item label="医院名称" name="hosname" rules={[{ required: true, message: '请输入医院名称!', transform(value){return value.trim()} }]}>
            <Input />
          </Form.Item>
          <Form.Item label="医院编号" name="hoscode" rules={[{ required: true, message: '请输入医院编号!' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="api基础路径" name="apiUrl" rules={[{ required: true, message: '请输入api基础路径!', transform(value){return value.trim()}}]}>
            <Input />
          </Form.Item>
          <Form.Item label="联系人姓名" name="contactsName" rules={[{ required: true, message: '请输入联系人姓名!' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="联系人手机" name="contactsPhone" rules={[{ required: true, message: '请输入联系人手机!', transform(value){return value.trim()}}]}>
            <Input />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 2, span: 22 }}>
            <Button
              type="primary"
              htmlType="submit"
              className={style.saveHospitalInf}
            >
              保存
            </Button>
            <Button type="default" onClick={goBackToLastHandle}>
              返回
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
